package com.ruoyi.aitu9c.service;

import com.ruoyi.aitcommon.anotation.ServiceLog;
import com.ruoyi.aitcommon.utils.FileUtils;
import com.ruoyi.aitcommon.utils.XmlUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class U9UtilService {
    @ServiceLog("将ubf文件转换为md文件")
    public void U9XML2Text(String xmlname, String textname, Map<String,Object> dtmap) throws Exception {
        StringBuilder sb=new StringBuilder();
        Map<String,Object> sysgroup=new HashMap<String,Object>(){
            private static final long serialVersionUID = 1L;
            {
                put("Sys","Sys");
                put("Key","Key");
            }};
        Document xml = XmlUtils.load(xmlname);
        Element root = xml.getRootElement();
//		依据xpath获取PropertyType节点
        List<Element> nodes = root.selectNodes("/Component/Namespace/PropertyType");
//		遍历所有PropertyType节点
        for(Element el:nodes) {
            String elstr="# %s-%s\r\n";
            elstr=String.format(elstr, el.attributeValue("name"),el.attributeValue("displayName"));
//			System.out.print(elstr);
            sb.append(elstr);
            sb.append("| **字段名称** | **中文名称** | **字段类型** | **说明** | \r\n"
                    + "| --- | --- | --- | --- | \r\n");
//			获取PropertyType节点下的Attribute节点
            List<Element> nodes2 = el.selectNodes("Attributes/Attribute");
            for(Element el2:nodes2) {
//				排除掉系统分组
                String group=el2.attributeValue("groupName");
                if(sysgroup.containsKey(group)) continue;
//				通过映射翻译类型
                String dtkey = el2.attributeValue("dataTypeID");
                String dtvalue="";
                String df = el2.attributeValue("defaultValue");
                if(dtmap!=null&&dtmap.containsKey(dtkey)) {
                    dtvalue=dtmap.get(dtkey).toString();
                }else if(df.equals("-1")) {
                    dtvalue="枚举";
                }
//				输出md表格
                String elstr2="| %s | %s | %s | | \r\n";
                elstr2=String.format(elstr2, el2.attributeValue("name"),el2.attributeValue("displayName"),dtvalue);
//				System.out.print(elstr2);
                sb.append(elstr2);
            }
        }
//		写入文件
        FileUtils.writeFile(textname, sb.toString());
    }
}
